package org.ourgrid.broker.business.schedulerdata.executor;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.common.interfaces.to.IncomingHandle;
import org.ourgrid.common.interfaces.to.OutgoingHandle;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.response.CancelIncomingTransferResponseTO;
import org.ourgrid.common.internal.response.CancelOutgoingTransferResponseTO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CancelTransferExecutor extends AbstractSchedulerDataExecutor {

	/**
	 * 
	 * <CANCEL_TRANSFER handleId='long' fileName='String' description='String' id='String'
	 * fileSize='long' outgoing='boolean'/> 
	 * 
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		long handleId = Long.valueOf(element.getAttribute("handleId"));
		String localFileName = element.getAttribute("localFileName");
		String description = element.getAttribute("description");
		String id = element.getAttribute("id");
		long fileSize = Long.valueOf(element.getAttribute("fileSize"));
		boolean outgoing = Boolean.valueOf(element.getAttribute("outgoing"));
		
		if (outgoing) {
			CancelOutgoingTransferResponseTO to = new CancelOutgoingTransferResponseTO();
			
			OutgoingHandle outgoingHandle = new OutgoingHandle(handleId, localFileName, new File(localFileName), description, id);
			
			to.setOutgoingHandle(outgoingHandle);
			
			responses.add(to);
		} else {
			CancelIncomingTransferResponseTO to = new CancelIncomingTransferResponseTO();
			
			IncomingHandle incomingHandle = new IncomingHandle(handleId, localFileName, fileSize, description, id);
			
			to.setIncomingHandle(incomingHandle);
			
			responses.add(to);
		}
		
		return responses;
	}
}
